package com.spzx.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.vo.ProductSkuVo;
import com.spzx.user.domain.UserCollect;
import com.spzx.user.mapper.UserCollectMapper;
import com.spzx.user.service.IUserCollectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户收藏表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2024-11-18
 */
@Service
public class UserCollectServiceImpl extends ServiceImpl<UserCollectMapper, UserCollect> implements IUserCollectService {

    private String getCollectKey(Long userId) {
        return "user:"+userId+":collect";
    }
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserCollectMapper userCollectMapper;



    @Override
    public void collect(Long skuId) {
        // 获取当前登录用户的ID
        Long userId = SecurityUtils.getLoginUser().getUserid();
        String userName = SecurityUtils.getLoginUser().getUsername();

        // 构建“用户”收藏的Hash结构Key，格式为 user:用户ID:collect
        String collectKey = getCollectKey(userId);

        // 创建Hash结构绑定操作对象，便于对Hash进行操作
        BoundHashOperations<String, String, UserCollect> hashOps = redisTemplate.boundHashOps(collectKey);
        Long count = hashOps.size();

        if (++count > 99) {
            // 收藏夹中商品数量已达到上限，不能再添加商品
            throw new ServiceException("收藏夹中商品数量已达到上限");
        }
        if (Boolean.TRUE.equals(hashOps.hasKey(skuId.toString()))) {
            // 该商品在收藏夹中已存在在缓存中，则直接返回
//            hashOps.delete(skuId.toString());
        } else {
        // 该商品在收藏夹中不存在，则查询数据库是否存在，如果存在，则更新数据库更新时间，并更新缓存
            if (
                    (userCollectMapper.selectCount(
                    new LambdaQueryWrapper<UserCollect>()
                            .eq(UserCollect::getUserId, userId)
                            .eq(UserCollect::getSkuId, skuId)
                    ) > 0)
            ) {
                // 该商品在收藏夹中已存在，更新数据库更新时间
                userCollectMapper.update(
                        null,
                        new LambdaQueryWrapper<UserCollect>()
                                .eq(UserCollect::getUserId,userId)
                                .eq(UserCollect::getUpdateBy, userName)
                );
            } else if (userCollectMapper.selectCount(
                    new LambdaQueryWrapper<UserCollect>()
                            .eq(UserCollect::getUserId, userId)
                            .eq(UserCollect::getSkuId, skuId)
                            .eq(UserCollect::getDelFlag, "2")
            ) > 0) {
                //将delflag字段设置为0并更新updataby字段
                userCollectMapper.update(
                        null,
                        new LambdaQueryWrapper<UserCollect>()
                                .eq(UserCollect::getUserId,userId)
                                .eq(UserCollect::getSkuId,skuId)
                                .eq(UserCollect::getDelFlag, "2")
                                .eq(UserCollect::getUpdateBy, userName)
                );
            } else {
                // 该商品在收藏夹中不存在，则插入数据库，并更新缓存
                UserCollect userCollect = new UserCollect();
                userCollect.setUserId(userId);
                userCollect.setSkuId(skuId);
                userCollect.setCreateBy(userName);
                hashOps.put(skuId.toString(), userCollect);
                userCollectMapper.insert(userCollect);
            }
        }
    }

    @Override
    public void cancelCollect(Long skuId) {

        // 获取当前登录用户的ID
        Long userId = SecurityUtils.getLoginUser().getUserid();

        // 构建“用户”收藏的Hash结构Key，格式为 user:用户ID:collect
        String collectKey = getCollectKey(userId);

        // 创建Hash结构绑定操作对象，便于对Hash进行操作
        BoundHashOperations<String, String, UserCollect> hashOps = redisTemplate.boundHashOps(collectKey);

        if (Boolean.TRUE.equals(hashOps.hasKey(skuId.toString()))) {
            // 该商品在收藏夹中已存在，删除该商品
            hashOps.delete(skuId.toString());
            // 同时更新数据库数据
            userCollectMapper.delete(
                    new LambdaQueryWrapper<UserCollect>()
                            .eq(UserCollect::getUserId, userId)
                            .eq(UserCollect::getSkuId, skuId)
            );
        }
    }

    @Override
    public boolean isCollect(Long skuId) {
        // 获取当前登录用户的ID
        Long userId = SecurityUtils.getLoginUser().getUserid();
        Boolean b = redisTemplate.boundHashOps(getCollectKey(userId)).hasKey(skuId.toString());
        if (b){
            return true;
        }else {
            LambdaQueryWrapper<UserCollect> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(UserCollect::getUserId,userId);
            lambdaQueryWrapper.eq(UserCollect::getSkuId,skuId);
            return userCollectMapper.selectCount(lambdaQueryWrapper) > 0;
        }
    }

    @Autowired
    private RemoteProductService remoteProductService;
    @Override
    public List<ProductSkuVo> getUserCollectList() {
        return super.lambdaQuery()
                .eq(UserCollect::getUserId, SecurityUtils.getLoginUser().getUserid())
                .list()
                .stream()
                .map(userCollect -> remoteProductService
                        .getProductSku(userCollect.getSkuId(), SecurityConstants.INNER)
                        .getData())
                .collect(Collectors.toList());
    }
}
